package com.jinzhi.jzweb.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CertificateNewsDO;
import com.jinzhi.jzweb.domain.CertificateProfileDO;
import com.jinzhi.jzweb.domain.TestPaperTemplateDO;
import com.jinzhi.jzweb.service.CertificateNewsService;
import com.jinzhi.jzweb.service.CertificateProfileService;
import com.jinzhi.jzweb.service.TestPaperTemplateService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 试卷模板
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/testPaperTemplate")
public class TestPaperTemplateController extends BaseController {
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private UserService userService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;

    @GetMapping()
    @RequiresPermissions("jzweb:testPaperTemplate:testPaperTemplate")
    String TestPaperTemplate() {
        return "jzweb/testPaperTemplate/testPaperTemplate";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:testPaperTemplate:testPaperTemplate")
    public Result<Page<TestPaperTemplateDO>> list(TestPaperTemplateDO testPaperTemplateDTO) {
        Wrapper<TestPaperTemplateDO> wrapper = new EntityWrapper<TestPaperTemplateDO>().orderBy("id", false);
        // 区分资源库试卷模块 资源库试卷模板通过关联表关联 无证书id
        wrapper.isNotNull("news_id");
        if (testPaperTemplateDTO.getState() != null) {
            wrapper.eq("state", testPaperTemplateDTO.getState());
        }
        if (testPaperTemplateDTO.getType() != null) {
            wrapper.eq("type", testPaperTemplateDTO.getType());
        }
        if (testPaperTemplateDTO.getName() != null) {
            wrapper.like("name", testPaperTemplateDTO.getName());
        }
        if (StringUtils.isNotBlank(testPaperTemplateDTO.getNewsName())) {
            Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name", testPaperTemplateDTO.getNewsName());
            List<CertificateProfileDO> certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
            String str = "";
            for (CertificateProfileDO certificateProfileDO : certificateProfileDOS) {
                List<CertificateNewsDO> certificateNewsDOs = certificateNewsService.findByKv("profile_id", certificateProfileDO.getId());
                for (CertificateNewsDO certificateNewsDO1 : certificateNewsDOs) {
                    str = str + certificateNewsDO1.getId() + ",";
                }
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("news_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("news_id", null);
            }
        }

        Page<TestPaperTemplateDO> page = testPaperTemplateService.selectPage(getPage(TestPaperTemplateDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            TestPaperTemplateDO obj = (TestPaperTemplateDO) page.getRecords().get(i);
            if (obj.getCreaterId() != null) {
                UserDO userDO = userService.getByUserId(obj.getCreaterId());
                if (userDO != null) {
                    obj.setCreaterName(userDO.getUsername());
                }
            }
            if (obj.getNewsId() != null) {
                Map<Object, Object> maps = certificateNewsService.selByNewName(obj.getNewsId());
                if (maps != null) {
                    if (maps.get("grade").equals(0)) {
                        obj.setNewsName(maps.get("name") + "(高级)");
                    } else if (maps.get("grade").equals(1)) {
                        obj.setNewsName(maps.get("name") + "(中级)");
                    } else if (maps.get("grade").equals(2)) {
                        obj.setNewsName(maps.get("name") + "(初级)");
                    }
                }
            }

            list.add(obj);


        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:testPaperTemplate:add")
    String add(Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByNewId());
        return "jzweb/testPaperTemplate/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:testPaperTemplate:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByNewId());
        TestPaperTemplateDO testPaperTemplate = testPaperTemplateService.selectById(id);
        model.addAttribute("testPaperTemplate", testPaperTemplate);
        return "jzweb/testPaperTemplate/edit";
    }

    @Log("添加试卷模板")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:testPaperTemplate:add")
    public Result<String> save(TestPaperTemplateDO testPaperTemplate) {
        TestPaperTemplateDO testPaperTemplates = testPaperTemplateService.findOneByKv("news_id", testPaperTemplate.getNewsId(), "type", testPaperTemplate.getType());
        if (testPaperTemplates != null) {
            return Result.fail("该证书的该考试类型已有试卷模板，请勿重复添加");
        }
        testPaperTemplate.setCreaterId(this.getUserId());
        testPaperTemplateService.insert(testPaperTemplate);
        return Result.ok();
    }

    @Log("修改试卷模板")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:testPaperTemplate:edit")
    public Result<String> update(TestPaperTemplateDO testPaperTemplate) {
        List<TestPaperTemplateDO> testPaperTemplates = testPaperTemplateService.findByKv("news_id", testPaperTemplate.getNewsId(), "type", testPaperTemplate.getType());
        if (testPaperTemplates != null && testPaperTemplates.size() > 0) {
            if (testPaperTemplates.size() == 1) {
                if (testPaperTemplates.get(0).getId().equals(testPaperTemplate.getId())) {
                    boolean update = testPaperTemplateService.updateById(testPaperTemplate);
                    return update ? Result.ok() : Result.fail();
                }
            }
            return Result.fail("该证书的该考试类型已有试卷模板，请勿重复");
        }
        boolean update = testPaperTemplateService.updateById(testPaperTemplate);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除试卷模板")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:testPaperTemplate:remove")
    public Result<String> remove(Long id) {
        testPaperTemplateService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除试卷模板")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:testPaperTemplate:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        testPaperTemplateService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

}
